$(function () {
    //获取url
    var url = localStorage.getItem("ajaxUrl");
    var pass = 1;
    var upData = {};
    var supplier_name_short = {};
    var describe = "";

    //批号   获取 焦点
    $("input#goods_id").focus();

    //点击返回箭头 清除 缓存 打开 storekeeper.html
    $(".head .goBack").on("click", function () {
        window.location.href = "init.html";
    });

    $("input.gg").on("focus", function (event) {
        if ($("select.gys").val()) {
            $(".content ul.ul_supplier").empty();
            $.popup(".popup-addGoods");
            $("aside .searchbar #search_supplier").focus()
        } else {
            $alert("请选择厂家");
        }
    });

    $(".popup-addGoods").on("click", ".head .pull-left", function () {
        $(".content ul.ul_supplier").empty();
        $.closeModal(".popup-addGoods");
    });

    //点击搜索 或 回车
    $("aside .searchbar").on("click", "a.button", function () {
        var val = $("aside .searchbar .search_supplier").val();
        if (val == "") {
            $alert("请输入关键字！");
            return;
        } else if (val.length < 2) {
            $alert("请输入至少2个字符！");
            return;
        }
        showCustomer();
        //显示加载提示符
        $(".popup_content .infinite-scroll-preloader").show();
    });
    $("aside .searchbar").on("keyup", ".search_supplier", function (event) {
        if (event.keyCode == "13") {
            var val = $(this).val();
            if (val == "") {
                $alert("请输入关键字！");
                return;
            } else if (val.length < 2) {
                $alert("请输入至少2个字符！");
                return;
            }
            showCustomer();
            //显示加载提示符
            $(".popup_content .infinite-scroll-preloader").show();
        }
    });
    //Ajax获取规格型号 添加进页面
    function showCustomer() {
        var val = $("aside .searchbar .search_supplier").val();
        $.ajax({
            headers: {authorization: "Bearer " + localStorage.getItem("jwt")},
            type: "POST",
            url: url + "/app/init/getWirerodSpecification",
            data: {
                gc: $("select.gys").val(),
                specification: val
            },
            dataType: "json",
            success: function (res) {
                $("aside .searchbar .search_supplier").val("");
                //隐藏加载提示符
                $(".popup_content .infinite-scroll-preloader").hide();
                var data = res.result;
                if (data.length == 0) {
                    $alert("产品规格型号不存在！");
                    return;
                }
                if (data.length > 0) {
                    $(".popup_content ul.ul_supplier").empty();
                    var con_html = "";
                    for (var i = 0; i < data.length; i++) {
                        var data_val = data[i].inventoryCode + "," + data[i].inventoryName + "," + data[i].inventorySpecification;
                        con_html += '<li class="customer_li" data-ggxh="' + data[i].inventorySpecification + '" data-name="' + data[i].inventoryName + '" data-code="' + data[i].inventoryCode + '">' + data_val + '</li>';
                    }
                    $(".popup_content ul.ul_supplier").append(con_html);
                }
            },
            error: function (error) {
                console.log("产品规格型号查询失败");
                $alert(error.responseText);
                //隐藏加载提示符
                $(".popup_content .infinite-scroll-preloader").hide();
            }
        });
    }

    //选择规格型号 添加到 缓存model
    $(".popup_content ul.ul_supplier").on("click", ".customer_li", function () {
        var name = $(this).attr("data-name");
        var code = $(this).attr("data-code");
        var ggxh = $(this).attr("data-ggxh");
        $("input.gg").val(ggxh).attr("data-code", code);
        $("input.pm").val(name);
        $.closeModal(".popup-addGoods");
    });

    $("input.vendor").on("keydown", function (event) {
        if (event.keyCode == "13") {
            var val = $(this).val();
            if (!val) {
                $alert("请输入供应商！");
                setTimeout(function () {
                    $("input.gg").val("").focus();
                }, 1400);
                return;
            } else {
                $.ajax({
                    headers: {authorization: "Bearer " + localStorage.getItem("jwt")},
                    url: url + "/app/init/getWirerodVendor",
                    type: "post",
                    data: {
                        name: val
                    },
                    dataType: "json",
                    json: "callback",
                    cache: false,
                    success: function (res) {
                        if (res.success) {
                            var data = res.result;
                            //console.log(data);
                            if (data.length == 0) {
                                $alert("供应商不存在！");
                                $(".content .vendor").attr("data-code", "");
                                $("input.vendor").val("")
                            } else if (data.length == 1) {
                                $("input.vendor").val(data[0].vendorName);
                                $("input.vendor").attr("data-code", data[0].vendorCode);
                                $alert("供应商填充成功！");
                            } else {
                                $(".div_inventory .div_inventory_ul").empty();
                                var inventory_html = "";
                                for (var i = 0; i < data.length; i++) {
                                    inventory_html += '<li data-code = ' + data[i].vendorCode + '><span>' + data[i].vendorName + '</span></li>';
                                }
                                $(".div_inventory .p_title").html("请选择供应商：");
                                $(".div_inventory .div_inventory_ul").html(inventory_html);
                                $.popup('.popup-about');
                            }
                        } else {
                            $alert(res.message);
                        }
                    },
                    error: function (error) {
                        console.log(error);
                        $alert(error.responseText);
                        $(".content .gg").attr("data-code", "");
                        setTimeout(function () {
                            $("input.gg").val("").focus();
                        }, 1400);
                    }
                })
            }
        }
    });

    $("select.house").on("change", function () {
        var house = $(this).val();
        if (house == "X101") {
            var gys = $("select.gys").val();
            if (house == "X101" && gys && !$("input.vendor").val()) {
                var supplier = gys;
                //var supplierShort = gys.split("&&")[1];
                loading_show("获取供应商...");
                $.ajax({
                    headers: {authorization: "Bearer " + localStorage.getItem("jwt")},
                    type: "post",
                    url: url + '/app/init/getVendorBySupplier',
                    data: {
                        supplier: supplier
                    },
                    dataType: 'json',
                    json: 'callback',
                    cache: false,
                    success: function (res) {
                        if (res.success) {
                            var data = res.result;
                            $alert("供应商获取成功");
                            $("input.vendor").val(data.vendorName);
                            $("input.vendor").attr("data-code", data.vendorCode);
                        } else {
                            $alert(res.message);
                        }
                    },
                    error: function (error) {
                        console.log(error);
                        $alert(error.responseText);
                    }
                });
            }
        } else {

        }
    });

    //选择厂家
    $("select.gys").on("change", function () {
        var gys = $(this).val();
        var house = $("select.house").val();
        if (house == "X101" && gys && !$("input.vendor").val()) {
            var supplier = gys;
            //var supplierShort = gys.split("&&")[1];
            loading_show("获取供应商...");
            $.ajax({
                headers: {authorization: "Bearer " + localStorage.getItem("jwt")},
                type: "post",
                url: url + '/app/init/getVendorBySupplier',
                data: {
                    supplier: supplier
                },
                dataType: 'json',
                json: 'callback',
                cache: false,
                success: function (res) {
                    loading_hide();
                    if (res.success) {
                        //$alert("供应商获取成功");
                        var data = res.result;
                        $("input.vendor").val(data.vendorName);
                        $("input.vendor").attr("data-code", data.vendorCode);
                    } else {
                        $alert(res.message)
                    }
                },
                error: function (error) {
                    loading_hide();
                    console.log(error);
                    $alert(error.responseText);
                }
            });
        }
    });

    //获取盘条厂家getWirerodfactorys
    getWirerodfactorys();
    //点击 刷新
    $("li.li-gys .icon-refresh-1-copy").on("click", function () {
        getWirerodfactorys();
    });

    //根据扫描内容 得到 盘条信息
    $("#goods_id").on("keydown", function (event) {
        if (event.keyCode == "13") {
            if (pass == 0) {
                return
            }
            pass = 0;
            var val = $(this).val();
            //$("#goods_id").blur();
            if (!val) {
                $alert("请扫描！");
                pass = 1;
                setTimeout(function () {
                    $("#goods_id").val("").focus();
                }, 1400);
                return;
            }
            var supplier = $("select.gys").val();
            if (!supplier) {
                pass = 1;
                $("#goods_id").val("");
                return $alert("请先选择厂家！");
            }
            if (!$(".content .house").val()) {
                pass = 1;
                $("#goods_id").val("");
                return $alert("请先选择仓库！");
            }
            //加载提示符 显示
            loading_show("搜索中...");
            //获取工单
            $.ajax({
                headers: {authorization: "Bearer " + localStorage.getItem("jwt")},
                type: "post",
                url: url + '/app/init/getWrierod',
                data: {
                    house: $(".content .house").val(),
                    supplier: supplier,
                    number: val
                },
                dataType: 'json',
                json: 'callback',
                success: function (res) {
                    pass = 1;
                    if (res.success) {
                        var data = res.result;
                        //加载提示符 隐藏
                        loading_hide();
                        $("#goods_id").val("");
                        //console.log(data);
                        if (data.batch) {
                            if (data.status == "已出库") {
                                $.alert("盘点异常," + data.status + "," + (data.outWay || "") + "", function () {
                                    $("#goods_id").val("").focus();
                                })
                            } else {
                                $alert("获取成功");
                                describe = val;
                                $("input.batch").val(data.batch);
                                $("select.gys").val(data.wirerodmanufacturerCode).trigger("change");
                                $("select.house").val(data.warehouseCode).trigger("change");
                                $("input.gg").val(data.inventorySpecification);
                                $("input.pm").val(data.inventoryName);
                                $("input.gg").attr("data-code", data.inventoryCode);
                                $("input.vendor").val(data.vendorName);
                                $("input.vendor").attr("data-code", data.vendorCode);
                                $("input.zl").val(data.quantity);
                                $("input.lh").val(data.stove);
                                $("input.jh").val(data.column);
                                //$("select.house").prop("disabled", true);
                            }
                        } else {
                            describe = val;
                            $("input.batch").val(data.number || "");
                            $("input.zl").val(data.weight);
                            $("input.lh").val(data.stove);
                            $("input.jh").val(data.colume);
                            //$("select.house").prop("disabled", false);
                            if (data.productnumbers.length == 1) {
                                $("input.gg").val(data.productnumbers[0].inventorySpecification);
                                $("input.pm").val(data.productnumbers[0].inventoryName);
                                $("input.gg").attr("data-code", data.productnumbers[0].inventoryCode);
                            } else {
                                $(".div_inventory .div_inventory_ul").empty();
                                var inventory_html = "";
                                for (var i = 0; i < data.productnumbers.length; i++) {
                                    inventory_html += '<li data-code = ' + data.productnumbers[i].inventoryCode + '><span>' + data.productnumbers[i].inventoryName + ',' + data.productnumbers[i].inventorySpecification + '</span></li>';
                                }
                                $(".div_inventory .p_title").html("请选择原料规格：");
                                $(".div_inventory .div_inventory_ul").html(inventory_html);
                                $.popup('.popup-about');
                            }
                        }

                    } else {
                        $alert(res.message);
                    }
                },
                error: function (error) {
                    pass = 1;
                    //加载提示符 隐藏
                    loading_hide();
                    console.log(error);
                    setTimeout(function () {
                        $("#goods_id").val("").focus();
                    }, 1400);
                    $alert(error.responseText);
                }
            });
        }
    });

    //点击 获取编号
    $(".foot").on("click", ".del_receive", function () {
        if (pass == 0) {
            return
        }
        pass = 0;
        $.ajax({
            headers: {authorization: "Bearer " + localStorage.getItem("jwt")},
            type: "post",
            url: url + '/app/init/getPtNumber',
            data: {},
            dataType: 'json',
            json: 'callback',
            cache: false,
            success: function (res) {
                pass = 1;
                if (res.success) {
                    $alert("获取成功");
                    $("input.batch").val(res.result.number);
                    $("select.house").prop("disabled", false);
                } else {
                    $alert(res.message);
                }
            },
            error: function (error) {
                pass = 1;
                console.log(error);
                $alert(error.responseText);
            }
        });
    });

    //点击 确认
    $(".foot").on("click", ".add_receive", function () {
        if (pass == 0) {
            return
        }
        pass = 0;
        //判断数据
        if (!$("input.batch").val()) {
            pass = 1;
            $alert("编号不可为空！");
            return;
        } else if (!$("select.gys").val()) {
            pass = 1;
            $alert("厂家不可为空！");
            return;
        } else if (!$("input.vendor").val()) {
            pass = 1;
            $alert("供应商不可为空！");
            return;
        } else if (!$("input.gg").val()) {
            pass = 1;
            $alert("规格不可为空！");
            return;
        } else if (!$("input.zl").val()) {
            pass = 1;
            $alert("重量不可为空！");
            return;
        }
        //获取 信息
        var batch = $(".content .batch").val();
        var gys = $(".content .gys").val();
        var house = $(".content .house").val();
        var gg = $(".content .gg").val();
        var ggCode = $(".content .gg").attr("data-code");
        var vendor = $(".content .vendor").val();
        var vendorcode = $(".content .vendor").attr("data-code");
        var zl = $(".content .zl").val();
        var stove = $(".content .lh").val();
        var column = $(".content .jh").val();
        if ($(".content .house").val() == "X101") {
            if (!stove) {
                pass = 1;
                $alert("炉号不可为空！");
                return;
            }
            if (!column) {
                pass = 1;
                $alert("卷号不可为空！");
                return;
            }
        }
        loading_show("入库中...");
        $.ajax({
            headers: {authorization: "Bearer " + localStorage.getItem("jwt")},
            type: "post",
            url: url + '/app/init/initWrierod',
            data: {
                batch: batch,
                describe: describe ? describe : batch,
                supplier: supplier_name_short[gys],
                supplierCode: gys,
                house: house,
                specification: gg,
                specificationCode: ggCode,
                vendorName: vendor,
                vendorCode: vendorcode,
                weight: zl,
                stove: stove,
                column: column
            },
            dataType: "json",
            json: "callback",
            timeout: 60000,
            cache: false,
            success: function (res) {
                pass = 1;
                loading_hide();
                if (res.success) {
                    var data = res.result;
                    $alert(batch + "盘点成功");
                    $(".content .batch").val("");
                    $(".content .zl").val("");
                    $(".content .jh").val("");
                    if (batch.indexOf("PT") > -1) {
                        $(".content .lh").val("");
                        $(".content .gg").val("");
                        $(".content .gg").attr("data-code","");
                    }
                    if (data.print && data.batch.indexOf("PT") == 0) {
                        upData = {
                            batch: data.batch,
                            gys: gys,
                            gg: gg,
                            zl: zl
                        };
                        cordova.plugins.print.wirerodpurchaseinorder(data.batch, gys, gg, zl, function (result) {
                        }, function error(error) {
                        });
                    }
                } else {
                    $alert(res.message);
                }
            },
            error: function (error) {
                pass = 1;
                if (error.status == 0) {
                    loading_hide();
                    $alert("请求超时，请重新提交！");
                } else {
                    loading_hide();
                    console.log(error);
                    $alert(error.responseText);
                }
            }
        });
    });

    //选中 某一个 数据  之后
    $(".div_inventory_ul").on("click", "li", function () {
        var data = $(this).text();
        var code = $(this).attr("data-code");
        var title = $(this).parent().prev().text();
        // console.log(data);
        // console.log(code);
        if (title.indexOf("规格") >= 0) {
            $("input.gg").val(data.split(',')[1]);
            $("input.pm").val(data.split(',')[0]);
            $("input.gg").attr("data-code", code);
            $.closeModal('.popup-about');
            $alert("规格选择成功！");
        } else if (title.indexOf("供应商") >= 0) {
            $("input.vendor").val(data);
            $("input.vendor").attr("data-code", code);
            $.closeModal('.popup-about');
            $alert("供应商选择成功！");
        }
    });

    //点击 关闭，清除输入框中数据
    $(".icon-guanbi").click(function () {
        $(this).hide().parent().parent().find("input").val("").focus();
        $(this).hide().parent().parent().find("input").attr("data-code", "");
    });

    function getWirerodfactorys() {
        $.ajax({
            headers: {authorization: "Bearer " + localStorage.getItem("jwt")},
            type: "post",
            url: url + '/app/init/getWirerodfactorys',
            data: {},
            dataType: 'json',
            json: 'callback',
            cache: false,
            success: function (res) {
                if (res.success) {
                    var data = res.result;
                    var data_html = '<option value="">请选择厂家</option>';
                    for (var i = 0; i < data.length; i++) {
                        data_html += '<option value="' + data[i].wirerodmanufacturerCode + '">' + data[i].wirerodmanufacturerNameShort + '</option>'
                        supplier_name_short[data[i].wirerodmanufacturerCode] = data[i].wirerodmanufacturerNameShort;
                    }
                    $("select.gys").html(data_html);
                    if (localStorage.getItem("pt_title")) {
                        var pt_title = JSON.parse(localStorage.getItem("pt_title"));
                        $("select.gys").val(pt_title.gys).trigger("change");
                    }
                    //$alert("厂家获取成功");
                } else {
                    $alert(res.message);
                }
            },
            error: function (error) {
                console.log(error);
                $alert(error.responseText);
            }
        });
    }

    //重打
    $(".head .icon-dayin").on("click", function () {
        if (upData.batch) {
            $alert(upData.batch + "打印成功");
            cordova.plugins.print.wirerodpurchaseinorder(upData.batch, upData.gys, upData.gg, upData.zl, function (result) {
            }, function error(error) {
            });
        } else {
            $alert("暂无数据");
        }
    });

});

